Linear Search Algorithm

The Linear Search Algorithm, also known as Sequential Search, is a simple and widely used technique for searching an element in a list or an array. It works by iterating through each element of the list or array, comparing the desired value with the current element. When a match is found, the algorithm returns the index of the matching element or indicates that the value has been found. If the desired value is not found after iterating through the entire list or array, the algorithm returns an indication that the value is not present. This method is particularly useful for small data sets or unsorted data, as it does not require any prior organization or sorting of the data. One of the key features of the Linear Search Algorithm is its simplicity, making it easy to implement and understand. However, its performance can be relatively slow for large data sets, as it may require examining every element before determining that the desired value is not present. The time complexity of the Linear Search Algorithm is O(n), where n is the number of elements in the list or array. In the best-case scenario, the desired value is found at the first position, requiring only one comparison, while in the worst-case scenario, the desired value is not present, requiring n comparisons. Despite its limitations, the Linear Search Algorithm remains a popular choice for basic searching tasks and serves as a foundation for understanding more complex search algorithms.
#include <iostream>
using namespace std;

int LinearSearch(int *array, int size, int key)
{
	for (int i = 0; i < size; ++i)
	{
		if (array[i] == key)
		{
			return i;
		}
	}

	return -1;
}

int main()
{
	int size;
	cout << "\nEnter the size of the Array : ";
	cin >> size;

	int array[size];
	int key;

	//Input array
	cout << "\nEnter the Array of " << size << " numbers : ";
	for (int i = 0; i < size; i++)
	{
		cin >> array[i];
	}

	cout << "\nEnter the number to be searched : ";
	cin >> key;

	int index = LinearSearch(array, size, key);
	if (index != -1)
	{
		cout << "\nNumber found at index : " << index;
	}
	else
	{
		cout << "\nNot found";
	}

	return 0;
}

LANGUAGE:

DARK MODE: